package com.hzit.pay.center.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hzit.pay.center.mapper.MchPayChannelInfoMapper;
import com.hzit.pay.center.model.MchInfo;
import com.hzit.pay.center.model.PaySerialNoInfo;
import com.hzit.pay.center.model.RefundSerialInfo;
import com.hzit.pay.center.service.*;
import com.hzit.pay.center.utils.AlipayUtil;
import com.pay.center.common.enums.PayChannelEnum;
import com.pay.center.common.enums.PayStatusEnum;
import com.pay.center.common.req.RefundReq;
import com.pay.center.common.utils.PayDigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class RefundServiceImpl implements IRefundService {

    @Autowired
    private MchPayChannelInfoMapper payChannelInfoMapper;


    @Autowired
    private IMchService mchService;

    @Autowired
    private IPaySerialNoService paySerialNoService;

    @Autowired
    private IRefundSerialService refundSerialService;


    @Autowired
    private AlipayUtil alipayUtil;

    @Override
    public void refund(RefundReq refundReq) {

        MchInfo mchInfo = mchService.queryMchInfoById(refundReq.getMchId());
        if (ObjectUtils.isEmpty(mchInfo)){
            //没有找到该商户
            return;
        }

        //1.验证签名
        JSONObject jsonObject = (JSONObject)JSONObject.toJSON(refundReq);
        String newSign = PayDigestUtil.getSign(jsonObject,mchInfo.getReqKey(),"sign");

        if (refundReq.getSign().equals(newSign)){
//            logger.info("订单号：{}，请求非法",paymentReq.getOrderId());
//            throw new BizException("该订单请求非法");
            return;
        }

       // 2.原始订单是否存在与数据库
        List<PaySerialNoInfo>  paySerialNoInfoList =  paySerialNoService.queryByOrderId(refundReq.getOriOrderId());

        if (CollectionUtil.isEmpty(paySerialNoInfoList)){

            //订单号不存在支付中心
            return;
        }

        //
        PaySerialNoInfo serialNoInfo = null;
        for (PaySerialNoInfo paySerialNoInfo :paySerialNoInfoList){

            //判断数据库中是否支付成功的流水
            if (PayStatusEnum.SUCCESS.getCode().equals(paySerialNoInfo.getPayStatus())){
                serialNoInfo = paySerialNoInfo;
            }
        }

        if (ObjectUtils.isEmpty(serialNoInfo)){

            //订单没有支付成功
            return;
        }

        //退款金额 <= 原订单金额
        BigDecimal refundAmt = new BigDecimal(refundReq.getRefundAmt());

        BigDecimal payAmt = serialNoInfo.getPayAmount();

        int result = refundAmt.subtract(payAmt).intValue();

        if (result>0){

            //退款金额 大于订单金额
            return;
        }

        //只允许一周内退款 配置的  和当前时间比较
        Date paySuccessTime = serialNoInfo.getPaySuccessTime(); //+ 7天
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, + 7);

        Date time =  c.getTime();

        Date date = new Date();

        //两个时间相差不能超过7天

        if (!time.before(date)){
            //超过最大退款期限
            return;
        }


        //查询订单是否存在退款流水表中
        List<RefundSerialInfo> serialInfoList = refundSerialService.queryByOrderId(refundReq.getOriOrderId());

        if (CollectionUtil.isEmpty(serialInfoList)){

            //创建退款流水
            RefundSerialInfo refundSerialInfo =  refundSerialService.createRefundSerial();

            sendRefundReq(refundSerialInfo,serialNoInfo.getBankType());

            //调用，退款接口
            return;


        }else {
            int count = 0;
            BigDecimal totalRefundAmt = new BigDecimal(0);
            for (RefundSerialInfo refundSerialInfo :serialInfoList ){

                if (refundSerialInfo.getRefundStatus().equals("0") //0成功的
                        || refundSerialInfo.getRefundStatus().equals("1")){ //退款中的
                    count = count++;

                    totalRefundAmt = totalRefundAmt.add(refundSerialInfo.getRefundAmount());
                }

            }

            //统计已经退款的金额 + 现在申请的金额 不能大于订单金额

            int result1 = totalRefundAmt.subtract(payAmt).intValue();

            if (result>0){

                //退款金额 大于订单金额
                return;
            }

            //退款笔数 统计成功的不能 超过我们配置的笔数

            if (count > 5){

                // 不让退
                return;
            }

            //退款失败的重新提交 调用退款接口

            sendRefundReq(serialInfoList.get(0),serialNoInfo.getBankType());

        }

    }


    /**
     * 发送退款请求
     * @param refundSerialInfo
     */
    private void sendRefundReq(RefundSerialInfo refundSerialInfo,String bankType){

        if (PayChannelEnum.ALIPAY.getCode().equals(refundSerialInfo.getRefundChannel())){
            //1.同步返回支付结果
            AlipayTradeRefundResponse response = alipayUtil.alipayRefund();

//            response.get

            //2.解析返回对象，拿到结果更新数据库状态，

            //3.封着通用对象返回。

        }else if(PayChannelEnum.WECHAT_PAY.getCode().equals(refundSerialInfo.getRefundChannel())){
            //1.调用微信的退款接口。
            //2.更新数据状态。微信处理中

            //20分钟就可以查询
            if ("OTHERS".equals(bankType)){
                //用零钱支付的进入。延时队列

                //消费者消费的时候，调用微信的退款查询接口

            }

        }


    }




}
